package com.zzp.basepresenter.util;


import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class SharePreferenceUtils {
    private static final String DEFAULT_SHAREPREFERENCE_NAME = "com.zx.ipfs";
    private static final String TAG = SharePreferenceUtils.class.getSimpleName();
    private static final long DEFAULT_SAVE_PERIOD = 5000L;
    private static final int ACTION_FOR_SAVE_PREFS = 1;
    private static final int ACTION_FOR_KEY_LISTENER = 2;
    private static Object sInitLock = new Object();
    private static Map<String, SharePreferenceUtils> sPreferences = new HashMap();
    private static List<String> sDoNotMigrateValueList = new ArrayList();
    private ConcurrentMap<String, String> mCurrentConfigurations = new ConcurrentHashMap();
    private SharedPreferences mPref;
    private Editor mEditor;
    private Vector<String> mDirty = new Vector();
    private Context mAppContext;
    private final String mAppDataDir;
    private final String mPrefName;
    private Object mModifyLock = new Object();
    private long mCurrentModifyTimer = 5000L;
    private Handler mHandler;
    protected WeakHashMap<String, HashSet<IOnSharedChangeListener>> listenersMap = new WeakHashMap();

    private SharePreferenceUtils(Context context, String prefName) {
        this.mAppContext = context.getApplicationContext() == null ? context : context.getApplicationContext();
        this.initCurrentConfigurations(prefName);
        this.mAppDataDir = context.getApplicationInfo().dataDir;
        this.mPrefName = prefName;
        this.mHandler = new Handler(context.getMainLooper()) {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        SharePreferenceUtils.this.commit(true);
                        break;
                    case 2:
                        HashSet<IOnSharedChangeListener> listeners = (HashSet) SharePreferenceUtils.this.listenersMap.get(msg.obj);
                        Iterator var3 = listeners.iterator();
                        while (var3.hasNext()) {
                            SharePreferenceUtils.IOnSharedChangeListener listener = (SharePreferenceUtils.IOnSharedChangeListener) var3.next();
                            listener.onSharedPreferenceChanged(msg.obj.toString());
                        }
                }

            }
        };
    }

    public static SharePreferenceUtils getInstance(Context context) {
        synchronized (sInitLock) {
            if (sPreferences.get(DEFAULT_SHAREPREFERENCE_NAME) == null) {
                try {
                    sPreferences.put(DEFAULT_SHAREPREFERENCE_NAME, new SharePreferenceUtils(context, DEFAULT_SHAREPREFERENCE_NAME));
                } catch (Exception var5) {
                    var5.printStackTrace();
                }
            }
        }

        return (SharePreferenceUtils) sPreferences.get(DEFAULT_SHAREPREFERENCE_NAME);
    }

    public void addOnSharedPreferenceChangListener(String key, SharePreferenceUtils.IOnSharedChangeListener listener) {
        if (TextUtils.isEmpty(key)) {
            throw new RuntimeException("key can not be null");
        } else if (listener == null) {
            throw new RuntimeException("listener can not be null");
        } else {
            if (this.listenersMap.get(key) == null) {
                HashSet<IOnSharedChangeListener> listeners = new HashSet();
                listeners.add(listener);
                this.listenersMap.put(key, listeners);
            }

            ((HashSet) this.listenersMap.get(key)).add(listener);
        }
    }

    private void initCurrentConfigurations(String prefName) {
        this.mPref = this.mAppContext.getSharedPreferences(prefName, 0);
        if (this.mPref != null) {
            Map<String, ?> map = this.mPref.getAll();
            if (map != null) {
                Iterator var3 = map.entrySet().iterator();

                while (var3.hasNext()) {
                    Entry<String, ?> entry = (Entry) var3.next();
                    if (!this.mDirty.contains(entry.getKey())) {
                        this.mCurrentConfigurations.put(entry.getKey(), String.valueOf(entry.getValue()));
                    }
                }
            }
        }

    }

    private String doMigrate(String key) {
        if (!TextUtils.isEmpty(key) && !sDoNotMigrateValueList.contains(key) && !sDoNotMigrateValueList.contains(this.mPrefName)) {
            Object result = null;
            if (isExistSharedPreferenceFile(this.mAppContext, key, this.mAppDataDir)) {
                Map<String, ?> map = this.mAppContext.getSharedPreferences(key, 0).getAll();
                Object temp = null;
                Iterator var5 = map.entrySet().iterator();

                while (var5.hasNext()) {
                    Entry<String, ?> entry = (Entry) var5.next();
                    String str = (String) entry.getKey();
                    temp = entry.getValue();
                    if (TextUtils.equals(key, str)) {
                        result = temp;
                    }

                    if (temp instanceof String) {
                        this.putString(str, String.valueOf(temp), false);
                    } else if (temp instanceof Integer) {
                        this.putInt(str, (Integer) temp, false);
                    } else if (temp instanceof Long) {
                        this.putLong(str, (Long) temp, false);
                    } else if (temp instanceof Boolean) {
                        this.putBoolean(str, (Boolean) temp, false);
                    }
                }

                deleteSharedPreferenceFile(this.mAppContext, key, this.mAppDataDir);
            }

            return result == null ? null : String.valueOf(result);
        } else {
            return null;
        }
    }

    public boolean hasKey(String key) {
        if (this.mCurrentConfigurations.containsKey(key)) {
            return true;
        } else {
            return this.doMigrate(key) != null ? this.mCurrentConfigurations.containsKey(key) : false;
        }
    }

    public String getString(String key, String defValue) {
        if (TextUtils.isEmpty(key)) {
            return defValue;
        } else {
            long current = -System.currentTimeMillis();
            String temp = (String) this.mCurrentConfigurations.get(key);
            if (temp != null) {
                return temp;
            } else if (this.mDirty.contains(key)) {
                return defValue;
            } else if (this.mPref != null) {
                if (this.mPref.contains(key)) {
                    temp = this.mPref.getString(key, defValue);
                    this.mCurrentConfigurations.put(key, temp);
                } else {
                    temp = this.doMigrate(key);
                    if (temp == null) {
                        temp = defValue;
                    }
                }

                return temp;
            } else {
                return defValue;
            }
        }
    }

    public boolean getBoolean(String key, boolean defValue) {
        try {
            String result = this.getString(key, String.valueOf(defValue));
            return Boolean.valueOf(result);
        } catch (ClassCastException var6) {
            try {
                if (this.mPref != null) {
                    return this.mPref.getBoolean(key, defValue);
                }
            } catch (Exception var5) {
            }

            return defValue;
        }
    }

    public int getInt(String key, int defValue) {
        int result = -2147483648;

        try {
            result = Integer.parseInt(this.getString(key, String.valueOf(defValue)));
        } catch (NumberFormatException var7) {
            Log.d(TAG, "Cannot cast defValue: " + defValue + " from sharepreference to int");
            result = defValue;
        } catch (ClassCastException var8) {
            try {
                if (this.mPref != null) {
                    return this.mPref.getInt(key, defValue);
                }
            } catch (Exception var6) {
                Log.d(TAG, "Cannot get int defValue: " + defValue);
            }

            Log.d(TAG, "Cannot cast defValue: " + defValue + " from sharepreference to int");
            result = defValue;
        }

        return result;
    }

    public float getFloat(String key, float defValue) {
        float result = defValue;

        try {
            String value = this.getString(key, (String) null);
            if (value != null) {
                result = Float.parseFloat(value);
            }
        } catch (NumberFormatException var7) {
            Log.d(TAG, "Cannot cast defValue: " + defValue + " from sharepreference to int");
            result = defValue;
        } catch (ClassCastException var8) {
            try {
                if (this.mPref != null) {
                    return this.mPref.getFloat(key, defValue);
                }
            } catch (Exception var6) {
                Log.d(TAG, "Cannot get int defValue: " + defValue);
            }

            Log.d(TAG, "Cannot cast defValue: " + defValue + " from sharepreference to int");
            result = defValue;
        }

        return result;
    }

    public long getLong(String key, long defValue) {
        long result = -9223372036854775808L;

        try {
            result = Long.parseLong(this.getString(key, String.valueOf(defValue)));
        } catch (NumberFormatException var9) {
            Log.d(TAG, "Cannot cast defValue: " + defValue + " from sharepreference to long");
            result = defValue;
        } catch (ClassCastException var10) {
            try {
                if (this.mPref != null) {
                    return this.mPref.getLong(key, defValue);
                }
            } catch (Exception var8) {
                Log.d(TAG, "Cannot get long defValue: " + defValue);
            }

            Log.d(TAG, "Cannot cast defValue: " + defValue + " from sharepreference to long");
            result = defValue;
        }

        return result;
    }

    public void putString(String key, String value, boolean saveImmediately) {
        if (this.mCurrentConfigurations != null) {
            this.mCurrentConfigurations.put(key, value);
            Message msg;
            if (saveImmediately && this.mPref != null) {
                if (this.mEditor == null) {
                    this.mEditor = this.mPref.edit();
                }

                this.mEditor.putString(key, value);
                this.mEditor.apply();
                synchronized (this.mModifyLock) {
                    this.mDirty.remove(key);
                }
            } else {
                synchronized (this.mModifyLock) {
                    this.mDirty.add(key);
                }

                this.mCurrentModifyTimer -= 100L;
                if (this.mCurrentModifyTimer < 0L) {
                    this.mCurrentModifyTimer = 0L;
                }

                this.mHandler.removeMessages(1);
                msg = this.mHandler.obtainMessage();
                msg.what = 1;
                this.mHandler.sendMessageDelayed(msg, this.mCurrentModifyTimer);
            }

            if (this.listenersMap.containsKey(key)) {
                msg = this.mHandler.obtainMessage();
                msg.obj = key;
                msg.what = 2;
                this.mHandler.sendMessageDelayed(msg, 0L);
            }

        }
    }

    public void putBoolean(String key, boolean value, boolean saveImmediately) {
        this.putString(key, String.valueOf(value), saveImmediately);
    }

    public void putInt(String key, int value, boolean saveImmediately) {
        this.putString(key, String.valueOf(value), saveImmediately);
    }

    public void putLong(String key, long value, boolean saveImmediately) {
        this.putString(key, String.valueOf(value), saveImmediately);
    }

    public void putFloat(String key, float value, boolean saveImmediately) {
        this.putString(key, String.valueOf(value), saveImmediately);
    }

    public void remove(String key, boolean saveImmediately) {
        this.mCurrentConfigurations.remove(key);
        if (saveImmediately && this.mPref != null) {
            if (this.mEditor == null) {
                this.mEditor = this.mPref.edit();
            }

            this.mEditor.remove(key);
            this.mEditor.apply();
        } else {
            synchronized (this.mModifyLock) {
                this.mDirty.add(key);
            }
        }

    }

    public void clear() {
        synchronized (this.mModifyLock) {
            this.mDirty.clear();
            this.mCurrentConfigurations.clear();
        }

        if (this.mPref != null) {
            if (this.mEditor == null) {
                this.mEditor = this.mPref.edit();
            }

            this.mEditor.clear();
            this.mEditor.apply();
        }

    }

    public static void save(boolean async) {
        synchronized (sInitLock) {
            SharePreferenceUtils temp;
            for (Iterator var3 = sPreferences.entrySet().iterator(); var3.hasNext(); temp.commit(async)) {
                Entry<String, SharePreferenceUtils> entry = (Entry) var3.next();
                temp = (SharePreferenceUtils) entry.getValue();
                if (temp.mHandler != null) {
                    temp.mHandler.removeMessages(1);
                }
            }

        }
    }

    private void commit(boolean asnyc) {
        if (this.mPref != null) {
            String temp = null;
            if (this.mEditor == null) {
                this.mEditor = this.mPref.edit();
            }

            synchronized (this.mModifyLock) {
                if (null == this.mDirty || this.mDirty.size() == 0) {
                    return;
                }

                Iterator var4 = this.mDirty.iterator();

                while (true) {
                    if (!var4.hasNext()) {
                        this.mDirty.clear();
                        this.mCurrentModifyTimer = 5000L;
                        break;
                    }

                    String key = (String) var4.next();
                    temp = (String) this.mCurrentConfigurations.get(key);
                    if (temp == null) {
                        this.mEditor.remove(key);
                    } else {
                        this.mEditor.putString(key, temp);
                    }
                }
            }

            if (asnyc) {
                if (VERSION.SDK_INT >= 9) {
                    this.mEditor.apply();
                } else {
                    this.mEditor.commit();
                }
            } else {
                this.mEditor.commit();
            }
        }

    }

    private static boolean isExistSharedPreferenceFile(Context context, String name, String appDataDir) {
        File sFile = getPreferenceFile(context, name, appDataDir);
        return sFile != null ? sFile.exists() : false;
    }

    private static boolean deleteSharedPreferenceFile(Context context, String name, String appDataDir) {
        File sFile = getPreferenceFile(context, name, appDataDir);
        return sFile != null && sFile.exists() ? sFile.delete() : false;
    }

    private static File getPreferenceFile(Context context, String name, String appDataDir) {
        return context != null && !TextUtils.isEmpty(name) && name.indexOf(File.separatorChar) < 0 ? new File(new File(appDataDir, "shared_prefs"), name + ".xml") : null;
    }

    public interface IOnSharedChangeListener {
        void onSharedPreferenceChanged(String var1);
    }
}
